<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Support\Facades\Log;

class UpdateWechatMenuCommand extends Command
{
    /**
     * 命令名称
     *
     * @var string
     */
    protected $signature = 'wechat:update-menu';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '更新微信公众号菜单栏';

    /**
     * 微信应用实例
     *
     * @var Application
     */
    protected $wxapp;

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        $this->wxapp = new Application(config('wechat.official_account.default'));
    }

    /**
     * 执行命令
     */
    public function handle()
    {
        $this->info('开始更新微信公众号菜单...');

        try {
            // 定义菜单结构
            $buttons = $this->getMenuButtons();

            // 创建菜单
            $client = $this->wxapp->getClient();
            $response = $client->postJson('/cgi-bin/menu/create', [
                'button' => $buttons
            ]);

            $result = json_decode($response->getContent(), true);

            if ($result['errcode'] === 0) {
                $this->info('微信菜单更新成功');
                Log::info('微信菜单更新成功');
                return 0;
            } else {
                $this->error('微信菜单更新失败：' . $result['errmsg']);
                Log::error('微信菜单更新失败：' . $result['errmsg']);
                return 1;
            }

        } catch (\Exception $e) {
            $this->error('更新微信菜单失败：' . $e->getMessage());
            Log::error('更新微信菜单失败：' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return 1;
        }
    }

    /**
     * 获取菜单按钮配置
     *
     * @return array
     */
    private function getMenuButtons()
    {
        return [
            [
                "name" => "黄瓜记账",
                "type" => "view",
                "url" => route('home')
            ],
            [
                "type" => "click",
                "name" => "领取7天会员",
                "key" => "GET_FREE_MEMBERSHIP"
            ]
        ];
    }
}
